package com.xizimall.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xizimall.mapper.TbContentMapper;
import com.xizimall.pojo.TbContent;
import com.xizimall.pojo.TbContentExample;
import com.xizimall.pojo.TbContentExample.Criteria;
import com.xizimall.service.ContentService;
import com.xizimall.common.pojo.EUDataGridResult;
import com.xizimall.common.pojo.XizimallResult;
import com.xizimall.common.utils.HttpClientUtil;
/**
 * 内容服务
 * <p>Title: ContentServiceImpl</p>
 * <p>Description: </p>
 * <p>华南理工大学研究生</p> 
 * @author	李隆熹
 * @date	2018年4月18日下午4:51:46
 * @version 1.0
 */
@Service
public class ContentServiceImpl implements ContentService {
  
	@Autowired
	TbContentMapper contentMapper;
	
	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	
	@Value("${REST_CONTENT_SYNC_URL}")
	private String REST_CONTENT_SYNC_URL;
	
	@Value("${REST_ITEMCAT_SYNC_URL}")
	private String REST_ITEMCAT_SYNC_URL;
	
	@Override
	public EUDataGridResult getContentList(int page, int rows, Long categoryId) {
		//创建查询条件
		TbContentExample example=new TbContentExample();
    	Criteria criteria=example.createCriteria();
    	criteria.andCategoryIdEqualTo(categoryId);
		//分页处理
		PageHelper.startPage(page, rows);
		List<TbContent>list=contentMapper.selectByExample(example);
		//创建返回对象
		EUDataGridResult result=new EUDataGridResult();
		result.setRows(list);
		PageInfo<TbContent>pageInfo=new PageInfo<>(list);
		result.setTotal(pageInfo.getTotal());
	    return result;
	}

	@Override
	public XizimallResult insertContent(TbContent content) {
		content.setCreated(new Date());
		content.setUpdated(new Date());
		contentMapper.insert(content);
		//添加缓存同步
		try {
			HttpClientUtil.doGet(REST_BASE_URL+REST_CONTENT_SYNC_URL+content.getCategoryId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return XizimallResult.ok();
	}

	@Override
	public XizimallResult editContent(TbContent content) {
		content.setCreated(contentMapper.selectByPrimaryKey(content.getId()).getCreated());
		content.setUpdated(new Date());
		contentMapper.updateByPrimaryKeyWithBLOBs(content);
		//添加缓存同步
				try {
					HttpClientUtil.doGet(REST_BASE_URL+REST_CONTENT_SYNC_URL+content.getCategoryId());
				} catch (Exception e) {
					e.printStackTrace();
				}
				return XizimallResult.ok();
			}

}
